package com.kun.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;

/**
 * @description: 腾讯云COS管理工具
 * @author: KM
 * 2018年5月6日 下午10:25:50
 */
public class UploadCosUtil {
	
	private static final Logger logger = LoggerFactory.getLogger(UploadCosUtil.class);
	
	private static COSCredentials cred;
	private static ClientConfig clientConfig;
	private static COSClient cosClient;
	private static String bucketName;
	static{
		//SecretId  SecretKey
        cred = new BasicCOSCredentials("AKID2xhGdrsmX7Wjkaigy65sVzIRO9i2BE3l","e9SZFoGYdidMtEMOFxToxuf8Q6e4LTP9");  
        // 2 设置bucket的区域, COS地域的简称请参照  
        clientConfig = new ClientConfig(new Region("ap-guangzhou"));  
        // 3 生成cos客户端  
        cosClient = new COSClient(cred, clientConfig); 
        //bucketName + -APPID
        bucketName = "deepfeel-1253391577";
	}
	
	/**
	 * 要上传的文件 file
	 * cos路径 cosPath
	 * 设置上传的文件名称 fileName
	 * */
	public static String picCOS(MultipartFile  file,String cosPath,String fileName) throws Exception {
		cosPath = cosPath + fileName;
		String localPath = "F://file//" + fileName;
		FileInputStream inputStream=(FileInputStream) file.getInputStream();
		File outFile = new File(localPath);
		OutputStream outputStream = new FileOutputStream(outFile);
	    byte[] buf = new byte[1024];
   	    while (true) {
		    int read = 0;
		    if (inputStream != null) {
		    	read = inputStream.read(buf);
		    }
		    if (read == -1) {
		    	break;
		    }
		    outputStream.write(buf, 0, read);
		}
	    outputStream.flush();
	    outputStream.close();
	    inputStream.close();
        
        // 指定要上传到 COS 上的路径  
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, cosPath, outFile);
        cosClient.putObject(putObjectRequest);  
        logger.info("上传COS成功："+cosPath);
        cosClient.shutdown();
        
        // 判断本地文件是否存在, 如果存在则删除
        if(outFile.exists()){
           outFile.delete();
        }
        
        return "https://deepfeel-1253391577.cos.ap-guangzhou.myqcloud.com" + cosPath;
		//Date expiration = new Date(new Date().getTime() + 5 * 60 * 10000);  
		//URL url = cosClient.generatePresignedUrl(bucketName, fileName, expiration);
		//return url.toString();
    } 
	
	public static int deleteCosPic(String key){
		int i = 0;
		if(key!=null&&!"".equals(key)&&!"/".equals(key)){
			cosClient.deleteObject(bucketName, key);
			logger.info("删除COS成功："+key);
			cosClient.shutdown();
			i = 1;
		}
		return i;
	}

}
